import json
import os

import sys

from PyQt5.QtWidgets import QDialog, QMessageBox, QFileDialog, QApplication

import FileRename
import FileRenameAll
from utils import remote_django_api


class FileRenameMain(FileRename.Ui_RenameFile, QDialog):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.show()

        # 保存到本地配置文件的设备选择
        self.config_file_device_select = "device_select_config.txt"

        # 从服务器获取配置
        self.django_process_config = remote_django_api.DjangoProcessConfig()
        self.init_device_names()

        # 从本地加载上次保存的选择配置
        self.load_select_device_info()

        # 一些字段不可以编辑的
        self.ProcessID_lineEdit.setReadOnly(True)
        self.ProcessName_lineEdit.setReadOnly(True)
        self.ProductType_lineEdit.setReadOnly(True)

        # 设备名称的下拉选择操作
        self.EquipmentID_comboBox.currentIndexChanged.connect(self.on_combobox_devicename_changed)
        # 点击保存配置的操作
        self.Set_pushButton.clicked.connect(self.save_select_device_info)
        # 查询型号操作
        self.LotNumberCheck_pushButton.clicked.connect(self.query_lot_number)
        # 多选文件的操作
        self.FileChoose_pushButton.clicked.connect(self.open_file_dialog)
        # 点击重命名
        self.FileRename_pushButton.clicked.connect(self.do_rename_action)

    def get_all_file_items(self):
        all_items = []
        for index in range(self.FileAddress_listWidget.count()):
            text = self.FileAddress_listWidget.item(index).text().strip()
            if text:
                all_items.append(text)
        return all_items

    def do_rename_action(self):
        equipment_id = self.EquipmentID_comboBox.currentText().strip()
        if not equipment_id:
            QMessageBox.warning(self, "信息提示", "请选择设备")
            return
        process_id = self.ProcessID_lineEdit.text().strip()
        if not process_id:
            QMessageBox.warning(self, "信息提示", "请输入工序号")
            return
        process_name = self.ProcessName_lineEdit.text().strip()
        if not process_name:
            QMessageBox.warning(self, "信息提示", "请输入工序名称")
            return
        lot_number = self.LotNumber_lineEdit.text().strip()
        if not lot_number:
            QMessageBox.warning(self, "信息提示", "请输入批次号")
            return
        product_type = self.ProductType_lineEdit.text().strip()
        if not product_type:
            QMessageBox.warning(self, "信息提示", "请输入型号")
            return
        operater = self.Operater_lineEdit.text().strip()
        if not operater:
            QMessageBox.warning(self, "信息提示", "请输入测试员")
            return
        filepaths = self.get_all_file_items()
        if not filepaths:
            QMessageBox.warning(self, "信息提示", "请选择要重命名的文件")
            return
        message = FileRenameAll.do_rename_files(equipment_id, process_id, process_name, lot_number, product_type,
                                                operater, filepaths)
        if message:
            QMessageBox.warning(self, "重命名报错", message)
            return
        else:
            QMessageBox.information(self, "重命名成功", "重命名成功")

    def open_file_dialog(self):
        """多选文件"""
        file_dialog = QFileDialog()
        file_dialog.setFileMode(QFileDialog.FileMode.ExistingFiles)
        file_ext = "All Files (*)"
        if self.ProcessID_lineEdit.text() == "101":
            file_ext = "Excel Files (*.xls)"
        elif self.ProcessID_lineEdit.text() == "102":
            file_ext = "CSV Files (*.csv)"
        elif self.ProcessID_lineEdit.text() == "103":
            file_ext = "Excel Files (*.xlsx)"
        file_paths, _ = file_dialog.getOpenFileNames(self, 'Select Files', '', file_ext)

        if file_paths:
            # 将选中的文件路径显示在文本编辑器中
            self.FileAddress_listWidget.clear()
            self.FileAddress_listWidget.addItems(file_paths)

    def query_lot_number(self):
        """查询ProductType对应的是型别，LotNumber对应的是批次号"""
        input_LotNumber = self.LotNumber_lineEdit.text()
        if not str(input_LotNumber):
            QMessageBox.warning(self, "提示", "请输入批次号，才能查询")
            return

        product_type = self.django_process_config.query_product_type(input_LotNumber)
        if not product_type:
            QMessageBox.warning(self, "提示", "这个批次号查询不到对应的型号")
            return

        self.ProductType_lineEdit.setText(product_type)

    def save_select_device_info(self):
        data = {
            "device_name": self.EquipmentID_comboBox.currentText(),
            "process_number": self.ProcessID_lineEdit.text(),
            "process_name": self.ProcessName_lineEdit.text(),
        }
        with open(self.config_file_device_select, "w") as f:
            f.write(json.dumps(data))

        QMessageBox.warning(self, "信息提示", "保存配置成功")

    def load_select_device_info(self):
        """加载上次选择的配置文件"""
        if os.path.isfile(self.config_file_device_select):
            datajson = {}
            with open(self.config_file_device_select) as f:
                datajson = json.loads(f.read())
            if "device_name" in datajson and "process_number" in datajson and "process_name" in datajson:
                self.EquipmentID_comboBox.setCurrentText(datajson.get("device_name"))
                self.ProcessID_lineEdit.setText(datajson.get("process_number"))
                self.ProcessName_lineEdit.setText(datajson.get("process_name"))

    def on_combobox_devicename_changed(self):
        select_devicename = self.EquipmentID_comboBox.currentText()
        print(select_devicename)
        process_number, process_name = self.django_process_config.get_process_info(select_devicename)
        self.ProcessID_lineEdit.setText(str(process_number))
        self.ProcessName_lineEdit.setText(str(process_name))

    def init_device_names(self):
        """初始化设备名字列表"""
        self.EquipmentID_comboBox.clear()
        self.EquipmentID_comboBox.addItem("请选择设备")
        self.EquipmentID_comboBox.addItems(self.django_process_config.get_device_names())


if __name__ == "__main__":
    app = QApplication(sys.argv)

    fileRenameMain = FileRenameMain()
    fileRenameMain.show()

    sys.exit(app.exec_())
